package model;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class Ball {

	private int x;
	private int y;
	
	public static final int SIZE = 8;
	public static final int SPEED = 2;
	public static final int MARGIN = 10;
	
	public static final Color COLOR = Color.WHITE;
	public static final Random RND = new Random();

	int dx;
	int dy;
	int scoreP;
	int scoreAI;

	public Ball() {
		this.x = Game.WIDTH / 2;
		this.y = Game.HEIGHT / 2;
		dx = RND.nextInt(2) + 1;
		dy = RND.nextInt(2) + 1;
		scoreP = 0;
		scoreAI = 0;
	}

	public void move() {
		x += SPEED * dx;
		y += SPEED * dy;
		handleBoundary();
	}

	public void draw(Graphics g) {
		Color savedCol = g.getColor();
		g.setColor(COLOR);
		g.fillRect(getX() - SIZE / 2, getY() - SIZE / 2, SIZE, SIZE);
		g.setColor(savedCol);		
	}

	protected void handleBoundary() {
		if (y + SIZE / 2 >= Game.HEIGHT - MARGIN || y - SIZE / 2 <= MARGIN)
			dy *= -1;
		if (isOutOfBounds()) {
			dx = 0;
			dy = 0;
		}
	}
	
	public void newBall() {
		this.x = Game.WIDTH / 2;
		this.y = Game.HEIGHT / 2;
	}
	
	public boolean isOutOfBounds() {
		if (x - SIZE / 2 >= Game.WIDTH - MARGIN || x - SIZE / 2 <= MARGIN)
			return true;
		return false;
	}
	
	public void checkCollision(Paddle p, AI ai) {
		
		int pTop = p.getY() - Paddle.SIZE_Y / 2;
		int pBot = p.getY() + Paddle.SIZE_Y / 2;
		int pLEdge = p.getX() - Paddle.SIZE_X / 2;
		int pREdge = p.getX() + Paddle.SIZE_X / 2;
		
		int aiTop = ai.getY() - AI.SIZE_Y / 2;
		int aiBot = ai.getY() + AI.SIZE_Y / 2;
		int aiLEdge = ai.getX() - AI.SIZE_X / 2;
		int aiREdge = ai.getX() + AI.SIZE_X / 2;
		
		if (y > pTop && y < pBot)
			if (x + SIZE / 2 == pLEdge || x - SIZE / 2 == pREdge)
				hitPaddle();
		
		if (y > aiTop && y < aiBot)
			if (x + SIZE / 2 == aiLEdge || x - SIZE / 2 == aiREdge)
				hitPaddle();
	}
	
	public void hitPaddle() {
		dx *= -1;
	}
	
	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}
	
	public int getScoreP() {
		return scoreP;
	}
	
	public int getScoreAI() {
		return scoreAI;
	}
	

}
